package com.affectu.dao.pagination;

import java.util.List;

import org.hibernate.Session;

import com.affectu.common.util.PersistanceUtil;

/**
 * Oct 13, 2008
 * 
 * @author daniel nathan
 */
public abstract class AffectuDataModel<T> extends BaseDataModel<T, Long> {

    private Session em = PersistanceUtil.getInstance().getSession();

    private String hql, countSql;

    public AffectuDataModel(String hql) {
        this.hql = hql;
    }

    public AffectuDataModel(String hql, String countSql) {
        this.hql = hql;
        this.countSql = countSql;
    }

    public abstract T findById(Long id);

    @Override
    public Long getCount() {
        Long count;
        if (countSql != null) {
            count = (Long) em.createSQLQuery(countSql).uniqueResult();
        } else {
            count = Long.valueOf(em.createQuery(hql).list().size());
        }
        return count;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<T> getList(Integer firstRow, Integer maxResults) {
        return em.createQuery(hql).setFirstResult(firstRow).setMaxResults(maxResults).list();
    }
}
